package com.pdstudio.photos;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nostra13.universalimageloader.core.*;
import com.nostra13.universalimageloader.core.display.*;
import com.pdstudio.app.Application;
import com.pdstudio.app.Application.EventHandler;
import com.pdstudio.bean.LiveImg;
import com.pdstudio.bean.ResponseData;
import com.pdstudio.http.LiveHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.weather.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/*
 * 相册管理*/
public class PhotoGalleryActivity extends Activity implements EventHandler {

	protected static final int TEXT = 0;
	protected static final int PRAISEOK = 1;// 点赞成功
	protected static final int PRAISEFAIL = 2;// 点赞失败
	public List<Map<String, Object>> meumList;
	public LayoutInflater inflater;
	public Map<String, Integer> fileMap;
	public Handler handler;
	public GridView gridview;
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;

	public List<LiveImg> imgs;// 服务器返回的数据

	int bitmapWidth, bitmapHeight;
	FrameLayout.LayoutParams image_params;
	ProgressBar pb;

	public Map<String, String> nicepics;// 存储动态生成的点赞图片的id与数据库对应的图片的id
	public int currentPicId;

	private ImageView iv_gra, iv_camera;// 相册或者相机选取图片
	private Intent doCamera;
	private static final int NONE = 0;
	private static final int PHOTO_GRAPH = 1;// 拍照
	private static final int PHOTO_ZOOM = 2; // 缩放
	private static final int PHOTO_RESOULT = 3;// 结果
	private static final String IMAGE_UNSPECIFIED = "image/*";

	private View customLiveIndexTitleView;
	private TextView txtTitle;
	private ImageView ivBack;

	DisplayImageOptions options;// 图片动态加载选项

	/*
	 * 更改当前选中pic的id
	 */
	public synchronized void ChangeId(int id) {
		this.currentPicId = id;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photogallery_main);
		
		
		Application.mListeners.add(this);
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		LinearLayout layout = (LinearLayout) findViewById(R.id.photogallery_main);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));
		
		customLiveIndexTitleView = findViewById(R.id.title_photogallery);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("天气实景");
		
		ivBack = (ImageView) findViewById(R.id.title2_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PhotoGalleryActivity.this.finish();

			}

		});


		initiaView();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == NONE)
			return;
		// 拍照
		if (requestCode == PHOTO_GRAPH) {
			// 设置文件保存路径
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == PHOTO_ZOOM) {
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == PHOTO_RESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				// Bitmap photo = extras.getParcelable("data");
				// ByteArrayOutputStream stream = new ByteArrayOutputStream();
				// photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);//
				// (0-100)压缩文件
				// 此处可以把Bitmap保存到sd卡中，具体请看：http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html
				// imageView.setImageBitmap(photo); //把图片显示在ImageView控件上
				Intent intent = new Intent(PhotoGalleryActivity.this,
						UploadPicActivity.class);
				intent.putExtra("data", extras.getParcelable("data"));
				startActivity(intent);
				PhotoGalleryActivity.this.finish();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 收缩图片
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 500);
		intent.putExtra("outputY", 500);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTO_RESOULT);
	}

	private void initiaView() {

		InitalImageLoaderOption();

		meumList = new ArrayList<Map<String, Object>>();
		fileMap = new HashMap<String, Integer>();
		inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);

		gridview = (GridView) findViewById(R.id.photogridview1);

		pb = (ProgressBar) findViewById(R.id.pb_progress_ga);

		nicepics = new HashMap<String, String>();

		doCamera = new Intent(this, DoCameraActivity.class);
		iv_gra = (ImageView) findViewById(R.id.photo_gra_gra);
		iv_gra.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Bundle b=new Bundle();
				// b.putBoolean("cwho", true);//true表示从相册取值
				// startActivity(doCamera,b);
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						IMAGE_UNSPECIFIED);
				startActivityForResult(intent, PHOTO_ZOOM);
			}

		});
		iv_camera = (ImageView) findViewById(R.id.photo_gra_camera);
		iv_camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Bundle b=new Bundle();
				// b.putBoolean("cwho", false);//false表示从照相取值
				// startActivity(doCamera,b);
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
						Environment.getExternalStorageDirectory(), "temp.jpg")));
				startActivityForResult(intent, PHOTO_GRAPH);
			}

		});

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		bitmapWidth = dm.widthPixels / 2;
		bitmapHeight = dm.widthPixels / 2;
		image_params = new FrameLayout.LayoutParams(bitmapWidth, bitmapHeight);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case TEXT:
					gridview.setAdapter(new PhotoGalleryAdapter());
					pb.setVisibility(View.GONE);
					break;
				case PRAISEOK:
					Toast.makeText(getApplicationContext(), "点赞成功！", 0).show();
					break;
				case PRAISEFAIL:
					Toast.makeText(getApplicationContext(), "点赞失败！", 0).show();
					break;
				default:
					break;
				}
			}
		};

		new Thread(new Runnable() {

			@Override
			public void run() {

				LiveHttpMethod lhm = new LiveHttpMethod(
						PhotoGalleryActivity.this);
				imgs = lhm.GetLiveImgs(mSpUtil.getAuthCode(), "2014-11-04", mApplication.getCurSimpleCity().cityCode);
				/*
				 * 2014-11-04取消直接获取到bitmap if (imgs != null) { for (int i = 0; i
				 * < imgs.size(); i++) { try { Map<String, Object> map = new
				 * HashMap<String, Object>(); Map<String, Object> bitmap = send(
				 * PhotoGalleryActivity.this, imgs.get(i).uri); if (map != null)
				 * { map.put("img", (Bitmap) (bitmap.get("img")));
				 * map.put("username", imgs.get(i).userName); map.put("id",
				 * imgs.get(i).id); map.put("uploadtime",
				 * imgs.get(i).uploadTime); map.put("praise",
				 * imgs.get(i).praise); meumList.add(map); }
				 * 
				 * } catch (Exception e) { e.printStackTrace(); } } }
				 */
				/*
				 * String[] path = new String[] {
				 * "http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg"
				 * ,
				 * "http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg"
				 * ,
				 * "http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg"
				 * ,
				 * "http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg"
				 * ,
				 * "http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg"
				 * }; for (int i = 0; i < path.length; i++) { Map<String,
				 * Object> map = new HashMap<String, Object>(); Map<String,
				 * Object> bitmap = send( PhotoGalleryActivity.this, path[i]);
				 * if (map != null) { map.put("img", (Bitmap)
				 * (bitmap.get("img"))); map.put("name", path[i]); map.put("id",
				 * i+""); meumList.add(map); } fileMap.put(path[i].toString(),
				 * (Integer) (bitmap.get("length"))); }
				 */
				handler.sendEmptyMessage(TEXT);
			}
		}).start();

		// 添加点击事件
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int index = arg2;// id是从0开始的
				//Toast.makeText(getApplicationContext(), "你按下了选项：" + index, 0)
				//		.show();
				switch (index) {
				default: {
				}
					break;
				}
				// Toast用于向用户显示一些帮助/提示
			}
		});
	}

	public Map<String, Object> send(Context context, String path) {
		Map<String, Object> map = new HashMap<String, Object>();
		ImageView imageView = null;
		imageView = new ImageView(context);
		// imageView.setMaxHeight(100);
		// imageView.setMaxWidth(100);
		Bitmap bitmap = null;
		try {
			URL url = new URL(path);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setConnectTimeout(5000);
			if (httpURLConnection.getResponseCode() == 200) {
				if (bitmap != null) {
					System.out.println("---" + bitmap);
					bitmap.recycle();
					System.gc();
				}
				InputStream is = httpURLConnection.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				// BitmapFactory.Options options = new BitmapFactory.Options();
				// options.inSampleSize = computeSampleSize(options, -1,
				// 128*128);
				// options.inJustDecodeBounds = true;
				int length = httpURLConnection.getContentLength();
				// System.out.println(httpURLConnection.get);
				// MediaStore
				map.put("img", bitmap);
				map.put("length", length);
			} else {
				Toast.makeText(context, "服务器端响应错误", Toast.LENGTH_LONG).show();
			}
			httpURLConnection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;

	}

	/*
	 * 设置动态加载图片的参数
	 */
	private void InitalImageLoaderOption() {
		options = new DisplayImageOptions.Builder()
		// .showImageOnLoading(R.drawable.w1) //设置图片在下载期间显示的图片
				.showImageForEmptyUri(R.drawable.w1)// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.w10) // 设置图片加载/解码过程中错误时候显示的图片
				// .cacheInMemory(true)//设置下载的图片是否缓存在内存中
				.cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
				// .considerExifParams(true) //是否考虑JPEG图像EXIF参数（旋转，翻转）
				// .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示
				// .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
				// .decodingOptions(android.graphics.BitmapFactory.Options
				// decodingOptions)//设置图片的解码配置
				// .delayBeforeLoading(int delayInMillis)//int
				// delayInMillis为你设置的下载前的延迟时间
				// 设置图片加入缓存前，对bitmap进行设置
				// .preProcessor(BitmapProcessor preProcessor)
				// .resetViewBeforeLoading(false)//设置图片在下载前是否重置，复位
				// .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
				.displayer(new FadeInBitmapDisplayer(100))// 是否图片加载好后渐入的动画时间
				.build();// 构建完成
	}

	/*
	 * 给图片点赞
	 */
	public void TakeNiceForPic(String viewid) {
		String picid = nicepics.get(viewid);
		// int id=Integer.parseInt(picid==null?"":picid);
		LiveHttpMethod live = new LiveHttpMethod(PhotoGalleryActivity.this);
		ResponseData rd = live.TakePicPraise(mSpUtil.getAuthCode(), currentPicId);
		if (rd != null && rd.getCode().equals("1")) {
			handler.sendEmptyMessage(PRAISEOK);
			// Toast.makeText(getApplicationContext(), "成功", 0).show();
		} else {
			handler.sendEmptyMessage(PRAISEFAIL);
			// Toast.makeText(getApplicationContext(), "失败", 0).show();
		}
	}

	public class PhotoGalleryAdapter extends BaseAdapter {

		private Context mContext;

		public PhotoGalleryAdapter(Context context) {
			this.mContext = context;
		}

		public PhotoGalleryAdapter() {
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return imgs.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return imgs.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		/*
		 * 2014-11-07更改图片加载方式
		 * 
		 * @Override public View getView(int position, View convertView,
		 * ViewGroup parent) { // TODO Auto-generated method stub View v =
		 * inflater.inflate(R.layout.photogallery_main_item, null); try {
		 * ImageView tx_name = (ImageView) v
		 * .findViewById(R.id.photoimageview1);
		 * tx_name.setLayoutParams(image_params); // TextView tx_phone =
		 * (TextView) v.findViewById(R.id.ItemText); Map<String, Object> map =
		 * meumList.get(position); if(map.get("img")!=null){
		 * tx_name.setImageBitmap((Bitmap) map.get("img")); } TextView iv1 =
		 * (TextView)v.findViewById(R.id.phototextview1);
		 * if(map.get("username")!=null){
		 * iv1.setText((String)map.get("username")); } TextView iv2 = (TextView)
		 * v.findViewById(R.id.phototextview2); if(map.get("uploadtime")!=null){
		 * iv2.setText((String)map.get("uploadtime")); } //
		 * tx_phone.setText((String) map.get("name")); TextView tv_npcount =
		 * (TextView) v .findViewById(R.id.photo_tv_nicepicount);
		 * if(map.get("praise")!=null){
		 * tv_npcount.setText((String)map.get("praise")); } ImageView iv_nicepic
		 * = (ImageView) v .findViewById(R.id.photo_iv_nicepic); if (map !=
		 * null) { String psi = position + ""; String imgid = map.get("id") ==
		 * null ? "0" : map.get("id") .toString(); nicepics.put(psi, imgid);
		 * iv_nicepic.setTag(imgid); }
		 * 
		 * iv_nicepic.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub Toast.makeText(getApplicationContext(), v.getTag() + "",
		 * Toast.LENGTH_SHORT).show(); ChangeId(Integer.parseInt(v.getTag() ==
		 * null ? "" : v .getTag().toString())); Thread thread = new Thread() {
		 * 
		 * @Override public void run() { TakeNiceForPic("0"); } };
		 * thread.start(); } }); } catch (Exception e) { e.printStackTrace(); }
		 * return v; }
		 */

		private String PhtoGalleryDateCut(String date) {
			String result = "";
			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date d = df.parse(date);
				if (d != null) {
					int year = d.getYear() + 1900;
					result = year + "/" + d.getMonth() + "/" + d.getDay();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = inflater.inflate(R.layout.photogallery_main_item, null);
			try {
				if (imgs != null && imgs.get(position) != null) {
					ImageView tx_name = (ImageView) v
							.findViewById(R.id.photoimageview1);
					tx_name.setLayoutParams(image_params);
					ImageLoader.getInstance().displayImage(
							imgs.get(position).uri, tx_name, options);
					TextView iv1 = (TextView) v
							.findViewById(R.id.phototextview1);
					iv1.setText(imgs.get(position).userName);
					TextView iv2 = (TextView) v
							.findViewById(R.id.phototextview2);
					iv2.setText(PhtoGalleryDateCut(imgs.get(position).uploadTime));
					TextView tv_npcount = (TextView) v
							.findViewById(R.id.photo_tv_nicepicount);
					tv_npcount.setText(imgs.get(position).praise);
					ImageView iv_nicepic = (ImageView) v
							.findViewById(R.id.photo_iv_nicepic);
					String psi = position + "";
					String imgid = imgs.get(position).id == null ? "0" : imgs
							.get(position).id + "";
					nicepics.put(psi, imgid);
					iv_nicepic.setTag(imgid);
					iv_nicepic.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							//Toast.makeText(getApplicationContext(),
							//		v.getTag() + "", Toast.LENGTH_SHORT).show();
							ChangeId(Integer.parseInt(v.getTag() == null ? ""
									: v.getTag().toString()));
							Thread thread = new Thread() {
								@Override
								public void run() {
									TakeNiceForPic("0");
								}
							};
							thread.start();
						}
					});

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return v;
		}

	}

	@Override
	public void onCityComplite() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNetChange() {
		// TODO Auto-generated method stub
		
	}

}
